package codec;

import bean.DemoProtocol;
import bean.GatewayProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

/**
 * Created by momochen on 2017-07-31.
 */
public class GatewayProtocolCodec extends ByteToMessageCodec<GatewayProtocol> {
    //除开数据区域  剩下的包长度
    public final int BASE_LENGTH = 2 + 1 + 2 + 1 + 2;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, GatewayProtocol gatewayProtocol, ByteBuf byteBuf) throws Exception {
        byteBuf.writeShort(gatewayProtocol.getHead());
        byteBuf.writeByte(gatewayProtocol.getSerial());
        byteBuf.writeShort(gatewayProtocol.getLenght());
        byteBuf.writeByte(gatewayProtocol.getCmd());
        byteBuf.writeBytes(gatewayProtocol.getDatas());
        byteBuf.writeShort(gatewayProtocol.getCrc());
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // 防止socket字节流攻击
        // 防止，客户端传来的数据过大
        // 因为，太大的数据，是不合理的
        if (byteBuf.readableBytes() > 2048) {
            byteBuf.skipBytes(byteBuf.readableBytes());
        }

        if (byteBuf.readableBytes() < BASE_LENGTH) {
            return;
        }

        byteBuf.markReaderIndex();
        GatewayProtocol gatewayProtocol = new GatewayProtocol();
        gatewayProtocol.setHead(byteBuf.readShort());
        gatewayProtocol.setSerial(byteBuf.readByte());
        short s = (short) ((short) (( byteBuf.readByte() & 0xFF) * 200) + (short) ( byteBuf.readByte() & 0xFF));
        gatewayProtocol.setLenght(s);
        gatewayProtocol.setCmd(byteBuf.readByte());

        if (gatewayProtocol.getLenght() - BASE_LENGTH < 0) {
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] bytes = new byte[gatewayProtocol.getLenght() - BASE_LENGTH];
        byteBuf.readBytes(bytes);
        gatewayProtocol.setDatas(bytes);

        gatewayProtocol.setCrc(byteBuf.readShort());

        list.add(gatewayProtocol);
    }
}
